<?php

class SiteController extends FeController {

    public function init() {
        parent::init();
        //update currency rating every time: 1hour
        Currency::model()->updateAllCurrency();
        //get currency of user and save session to show price of all products

        if (!Yii::app()->user->getState("current_user")) {
            $ipAdd = Yii::app()->ipAdd->getInfo();
            $currency = Countries::GetCurrencyByCountryCode($ipAdd->countryCode);
            Yii::app()->user->setState('ipAddress', $ipAdd); //bien nay de su dung cho form dang ky
            Yii::app()->user->setState('currency', $currency);
        }
    }

    public function actionIndex() {
        $slug = Yii::app()->settings->get('general', 'homepage');
        parent::renderPageSlug($slug);
    }

    public function allowedActions() {
        return 'index,logout';
    }

    public function actionLogin() {

        $serviceName = Yii::app()->request->getQuery('service');
        if (isset($serviceName)) {
            $eauth = Yii::app()->eauth->getIdentity($serviceName);
            $eauth->redirectUrl = Yii::app()->user->returnUrl;
            $eauth->cancelUrl = $this->createAbsoluteUrl('/login.html');

            try {
                if ($eauth->authenticate()) {
                    $identity = new EAuthUserIdentity($eauth);
                    //var_dump($eauth->getIsAuthenticated(), $eauth->getAttributes());
                    //successful authentication
                    if ($identity->authenticate()) {
                        $duration = 3600;
                        Yii::app()->user->login($identity, $duration);
                        $userid = Yii::app()->user->id;
                        $currency = Countries::GetCurrency($userid);
                        
                        Yii::app()->user->setState('currency', $currency);
                        if ($userid) {
                            $useradd = UserAddress::model()->findByAttributes(array('uid' => $userid, 'status' => 1));
                            $user = User::model()->findByPk($userid);
                            $userform = new UserLoginSocial();
                            $useraddform = new UserAddressSocial();
                            $userform->attributes = $user->attributes;
                            $useraddform->attributes = $useradd->attributes;
                            if (!$useraddform->validate()) {
                                Yii::app()->user->setFlash('warning', "Vui lòng cập nhật đây đủ thông tin!");
                                Yii::app()->user->setFlash('erroradd', CHtml::errorSummary($useraddform));
                                $eauth->redirectUrl = SITE_PATH_URL . 'user/updateAccount';
                            }
                            if (!$userform->validate()) {
                                Yii::app()->user->setFlash('warning', "Vui lòng cập nhật đầy đủ thông tin!");
                                Yii::app()->user->setFlash('erroruser', CHtml::errorSummary($userform));
                                $eauth->redirectUrl = SITE_PATH_URL . 'user/updateAccount';
                            }
                        }

                        $eauth->redirect();
                    } else {

                        $eauth->cancel();
                    }
                }
                // Something went wrong, redirect back to login page
                $this->redirect(array('site/login'));
            } catch (EAuthException $e) {
                // save authentication error to session              
                Yii::app()->user->setFlash('error', 'EAuthException: ' . $e->getMessage());
                // close popup window and redirect to cancelUrl
                $eauth->redirect($eauth->getCancelUrl());
            }
        }
    }

    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

    public function actionAddCart() {
        $currency = Yii::app()->user->getState('currency');
        $respon = $_POST['FormBuynow'];
        $id = $respon['object_id'];
        $qty = $respon['qty'];
        
        if ($qty < 1)
            $qty = 1;
        else if ($qty > 50)
            $qty = 50;
        $item = Object::model()->findByPk($id);

        if (isset($item)) {
            Yii::app()->shoppingCart->put($item, $qty);
            $items = Yii::app()->shoppingCart->getItemsCount();
            $total = Yii::app()->shoppingCart->getCost();
            $mess = "Đã thêm " . $qty . " thẻ " . $item->object_name . " vào giỏ hàng thành công";
        } else {
            $items = Yii::app()->shoppingCart->getItemsCount();
            $total = Yii::app()->shoppingCart->getCost();
            $mess = "";
        }
        $result = array();
        $result['cart'] = $items . " items (" . formatPrice($total) . " " . $currency . ")";
        $result['mess'] = $mess;

        echo json_encode($result);
        Yii::app()->end();
    }

    public function actioncheckout() {
        //echo json_encode($_POST);
        $amountTotal = 0;
        $result = array();
        $itemArr = $_POST['items'];
        $positions = Yii::app()->shoppingCart->getPositions();

        foreach ($positions as $pos) {
            $pid = $pos->id;
            $qty = $pos->getQuantity();
            $qty2 = intval($itemArr[$pid]['qty']);
            $price = $pos->getPrice();
            if ($qty != $qty2) {
                $item = Object::model()->findByPk($pid);
                Yii::app()->shoppingCart->update($item, $qty2);
                $qty = $qty2;
            }
            $amount = $price * $qty;
            $result['amount'][] = formatprice($amount);
        }
        $result['amountTotal'] = formatprice(Yii::app()->shoppingCart->getCost());
        echo json_encode($result);
    }

    public function actioncheckoutFinish() {
        //echo json_encode($_POST);
        $model = $_POST['CheckoutOrderForm'];
        $success = 0;
        $linkUrl = '';
        if ($_POST['changebilling'] != 0) {
            //truong hop thay doi billing
            $error1 = 0;
            $error2 = 0;
            $error3 = 0;
            $error4 = 0;
            if ($model['billing_street'] == '')
                $result['billing_street'] = 'empty';
            else {
                $result['billing_street'] = $model['billing_street'];
                $error1 = 1;
            }

            if ($model['billing_city'] == '')
                $result['billing_city'] = 'empty';
            else {
                $result['billing_city'] = $model['billing_city'];
                $error2 = 1;
            }

            if ($model['billing_region'] == '')
                $result['billing_region'] = 'empty';
            else {
                $result['billing_region'] = $model['billing_region'];
                $error3 = 1;
            }

            if ($model['billing_zipcode'] == '')
                $result['billing_zipcode'] = 'empty';
            else {
                $result['billing_zipcode'] = $model['billing_zipcode'];
                $error4 = 1;
            }
            //save new address in table user
            if ($error1 != 0 && $error2 != 0 && $error3 != 0 && $error4 != 0) {
                $uid = Yii::app()->user->id;
                $ipAdd = Yii::app()->ipAdd->getInfo();
                $address = UserAddress::model()->findByAttributes(array('uid' => $uid, 'status' => 1));
                $phone = $address->phone;
                $company = $address->company;
                $address->status = 0;
                $address->save(); // cap nhat status cho prev address;

                $add = new UserAddress();
                $add->uid = $uid;
                $add->phone = $phone;
                $add->company = $company;
                $add->street = $result['billing_street'];
                $add->city = $result['billing_city'];
                $add->region = $result['billing_region'];
                $add->zipCode = $result['billing_zipcode'];
                $add->countryCode = $ipAdd->countryCode;
                $add->ipAddress = ip();
                $add->modified = time();
                $add->created = time();
                $add->status = 1;
                $add->save();
                $success = 1;
            }
        } else {
            //truong hop ko thay doi billing
            $result['billing_street'] = $model['billing_street'];
            $result['billing_city'] = $model['billing_city'];
            $result['billing_region'] = $model['billing_region'];
            $result['billing_zipcode'] = $model['billing_zipcode'];
            $success = 1;
        }

        if ($success != 0) {
            $rscheckout = Yii::app()->checkout->checkoutProcess($model);
            $linkUrl = $rscheckout;
        }
        $result['linkURL'] = $linkUrl;
        echo json_encode($result);
    }

}
